package com.juyu.miliao.scheduler.service;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.common.constant.RedisKeys;
import com.juyu.miliao.common.constant.enumRedisKey.EnumRedisKey;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import com.juyu.miliao.common.util.ArrayUtil;
import com.juyu.miliao.scheduler.dao.mysql.UserInfoDao;
import com.juyu.miliao.scheduler.domin.User;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class SendPrivateMessageScheduler {
    private final Logger logger = LoggerFactory.getLogger(SendPrivateMessageScheduler.class);
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserInfoDao userInfoDao;

    @Scheduled(fixedDelay = 1000 * 20, initialDelay = 1000 * 55)
    public void sendPrivateMessage() {
        String hostUserId = stringRedisTemplate.opsForSet().randomMember(RedisKeys.SET_HOSTLINE_SEX.getValue(2));
        if (hostUserId == null || hostUserId.equals("")) {
            return;
        }
        Set<String> manUserSet = stringRedisTemplate.opsForSet()
                .members(EnumRedisKey.SET_USER_ONLINE_APPPACKAGEID_SEX.getValue("mmjy",1));
        Set<String> womanUserSet = stringRedisTemplate.opsForSet()
                .members(EnumRedisKey.SET_USER_ONLINE_APPPACKAGEID_SEX.getValue("mmjy",2));
        if (womanUserSet != null && womanUserSet.size() > 0) {
            manUserSet.addAll(womanUserSet);
        }
        if (manUserSet == null || manUserSet.size() == 0) {
            return;
        }
        User hostUser = userInfoDao.findUserById(Long.parseLong(hostUserId));
        Long[] userIdArray = manUserSet.stream().map(Long::parseLong)
                                    .collect(Collectors.toList()).toArray(new Long[manUserSet.size()]);
        if (userIdArray.length >= 450) {
            List<Long[]> subAry = ArrayUtil.splitAry(userIdArray, 450);//分割后的子块数组
            for (Long[] obj : subAry) {
                sendMessage(hostUser, obj);
            }
        }else{
            sendMessage(hostUser, userIdArray);
        }

    }

    private void sendMessage(User hostUser, Long[] userIdArray) {
        JSONObject bodyJSON = new JSONObject();
        bodyJSON.put("messageType", 1);
        JSONObject body = new JSONObject();
        body.put("userId", hostUser.getUserId());
        body.put("nickName", hostUser.getNickName());
        body.put("icon", hostUser.getIcon());
        body.put("message", "刚刚上传了一张私照");
        bodyJSON.put("body",body);
        JSONArray jsonArray = JSONArray.fromObject(userIdArray);
        try {
            String temp = NetEaseCloudUserService.sendBatchAttachMsg(bodyJSON.toString(), jsonArray.toString());
            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200"))
                logger.error("批量发送点对点自定义系统通知异常-云信：message={}", temp);
        } catch (Exception e) {
            logger.error("批量发送点对点自定义系统通知错误", e);
        }
    }

}

